package org.jeecgframework.tinydao.util;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;

public class FreemarkerParseFactory {

	private static final Configuration _tplConfig = new Configuration();

	public FreemarkerParseFactory() {
		 _tplConfig.setClassForTemplateLoading(this.getClass(), "/");
		 _tplConfig.setNumberFormat("0.#####################");
	}
	
	/** 
	* @Title: parseTemplate 
	* @Description: 解析ftl
	* @param @param tplName 模板名
	* @param @param encoding 编码
	* @param @param paras 参数
	* @param @return    设定文件 
	* @return String    返回类型 
	* @throws 
	*/
	public String parseTemplate(String tplName,String encoding,Map<String,Object> paras){
		try{
			StringWriter swriter = new StringWriter();
			encoding = encoding==null?"UTF-8":encoding;
			Template mytemp = _tplConfig.getTemplate(tplName, encoding);
			mytemp.process(paras, swriter);
			return swriter.toString();
		}catch(Exception e){
			e.printStackTrace();
			return e.toString();
		}
	}
	
	/** 
	* @Title: parseTemplateContent 
	* @Description: 解析ftl
	* @param @param tplContent 模板内容
	* @param @param paras 参数
	* @param @param encoding 编码
	* @param @return    设定文件  模板解析后内容
	* @return String    返回类型 
	* @throws 
	*/
	public String parseTemplateContent(String tplContent,Map<String,Object> paras,String encoding){
		Configuration cfg = new Configuration();
		StringWriter writer = new StringWriter();
		cfg.setTemplateLoader(new MyStringTemplateLoader(tplContent));
		encoding = encoding==null?"UTF-8":encoding;
		cfg.setDefaultEncoding(encoding);
		Template template;
		try{
			template = cfg.getTemplate("");
			template.process(paras, writer);
		}catch(Exception e){
			e.printStackTrace();
		}
		return writer.toString();
		
	}
	
	public String parseTemplateContent(String tplContent,Map<String,Object> paras){
		Configuration cfg = new Configuration();
		StringWriter writer = new StringWriter();
		cfg.setTemplateLoader(new MyStringTemplateLoader(tplContent));
		cfg.setDefaultEncoding("UTF-8");
		Template template ;
		try {
			template = cfg.getTemplate("");
			template.process(paras, writer);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return writer.toString();
	}
	
	
}
